import React, { useRef, useState } from 'react';
import ProTable from '@ant-design/pro-table';
import { Button, message, Space, Popconfirm, Switch, Tooltip, Modal } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { PlusOutlined, InfoCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { getAdminMenuList, setMenuDisable, setMenuUnauth, setMenuUnlogin, delMenu, setIsMenu } from '@/services/rule';
import Edit from './components/Edit';

const Index = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editId, setEditId] = useState(undefined);
  const [cateData, setCateData] = useState([]);
  const [lockId, setLockId] = useState('');

  const actionRef = useRef();

  const { confirm } = Modal;

  /**
   * 获取数据
   * 作者：糜家智
   * 时间：2021/8/2 18:03
   */
  const getData = async () => {
    const res = await getAdminMenuList();
    setCateData(res.data.list);
    return {
      data: res.data.list,
      success: true,
      total: res.data.count,
    };
  };

  /**
   * 模态框的显示和隐藏
   */
  const isShowModal = (show, id = null) => {
    setEditId(id);
    setIsModalVisible(show);
  };

  /**
   * 删除列
   * @param id
   * @returns {Promise<void>}
   */
  const handleOk = async (id) => {
    const res = await delMenu({ admin_menu_id: id });
    if (res.code === 200) {
      actionRef.current?.reload();
      message.success(res.msg);
    }
  };

  const tipText = (key) => {
    switch (key) {
      case 'is_disable':
        return (
          <>
            <span>是否禁用</span>
            <Tooltip title="开启后无法访问">
              <InfoCircleOutlined style={{ marginLeft: '2px' }} />
            </Tooltip>
          </>
        );
        break;
      case 'is_unauth':
        return (
          <>
            <span>无需权限</span>
            <Tooltip title="开启后不用分配权限也可以访问">
              <InfoCircleOutlined style={{ marginLeft: '2px' }} />
            </Tooltip>
          </>
        );
        break;
      case 'is_unlogin':
        return (
          <>
            <span>无需登录</span>
            <Tooltip title="开启后不用登录就可以访问">
              <InfoCircleOutlined style={{ marginLeft: '2px' }} />
            </Tooltip>
          </>
        );
        break;
      default:
        break;
    }
  };

  const handleStatus = async (aid, id, type) => {
    setLockId(aid + type);

    const setId = id === 0 ? 1 : 0;
    let res = {};

    switch (type) {
      case 'menu':
        res = await setIsMenu({ admin_menu_id: aid, is_menu: setId });
        actionRef.current?.reload();
        break;
      case 'disable':
        res = await setMenuDisable({ admin_menu_id: aid, is_disable: setId });
        break;
      case 'unauth':
        res = await setMenuUnauth({ admin_menu_id: aid, is_unauth: setId });
        break;
      case 'unlogin':

        if (setId == 1) {

          confirm({
            title: '确定要设置此菜单为无需登录吗？?',
            icon: <ExclamationCircleOutlined />,
            content: '开启后不用登录就可以访问！请根据需求设置!',
            onOk() {
              setMenuUnlogin({ admin_menu_id: aid, is_unlogin: setId }).then((result) => {
                if (result.code === 200) {
                  message.success(result.msg);
                }
                actionRef.current?.reload();
              });
            },
            onCancel() {},
          });

        }else{
          res = await setMenuUnlogin({ admin_menu_id: aid, is_unlogin: setId });
          actionRef.current?.reload();
        }

        break;
      default:
    }

    if (res.code === 200) {
      message.success(res.msg);
    }

    setLockId('');
  };

  const columns = [
    {
      title: '菜单名称',
      dataIndex: 'menu_name',
      key: 'menu_name',
    },
    {
      title: '菜单路由',
      dataIndex: 'menu_path',
      key: 'menu_path',
    },
    {
      title: '菜单链接(roles)',
      dataIndex: 'menu_url',
      key: 'menu_url',
    },
    {
      title: '排序',
      dataIndex: 'menu_sort',
      key: 'menu_sort',
    },
    {
      title: '菜单',
      dataIndex: 'is_disable',
      render: (_, record) => (
        <Switch
          checkedChildren="是"
          unCheckedChildren="否"
          // defaultChecked={record.is_menu === 1}
          checked={record.is_menu === 1}
          loading={record.admin_menu_id + 'menu' === lockId}
          onChange={async () => handleStatus(record.admin_menu_id, record.is_menu, 'menu')}
        />
      ),
    },
    {
      title: tipText('is_disable'),
      dataIndex: 'is_disable',
      render: (_, record) => (
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          defaultChecked={record.is_disable === 1}
          loading={record.admin_menu_id + 'disable' === lockId}
          onChange={async () => handleStatus(record.admin_menu_id, record.is_disable, 'disable')}
        />
      ),
    },
    {
      title: tipText('is_unauth'),
      dataIndex: 'is_unauth',
      render: (_, record) => (
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          defaultChecked={record.is_unauth === 1}
          loading={record.admin_menu_id + 'unauth' === lockId}
          onChange={async () => handleStatus(record.admin_menu_id, record.is_unauth, 'unauth')}
        />
      ),
    },
    {
      title: tipText('is_unlogin'),
      dataIndex: 'is_unlogin',
      render: (_, record) => (
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          // defaultChecked={record.is_unlogin === 1}
          checked={record.is_unlogin === 1}
          loading={record.admin_menu_id + 'unlogin' === lockId}
          onChange={async () => handleStatus(record.admin_menu_id, record.is_unlogin, 'unlogin')}
        />
      ),
    },
    {
      title: '修改时间',
      dataIndex: 'update_time',
      key: 'update_time',
    },
    {
      title: '操作',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => isShowModal(true, record.admin_menu_id)}>编辑</a>
          <Popconfirm
            title="确定删除么？"
            onConfirm={() => {
              handleOk(record.admin_menu_id);
            }}
            okText="确定"
            cancelText="取消"
          >
            <a href={'javascript'}>删除</a>
          </Popconfirm>
        </Space>
      ),
      hideInSearch: true,
    },
  ];

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        actionRef={actionRef}
        request={() => getData()}
        editable={{
          type: 'multiple',
        }}
        rowKey="admin_menu_id"
        search={false}
        pagination={false}
        dateFormatter="string"
        headerTitle="菜单列表"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => isShowModal(true)}
          >
            新建
          </Button>,
        ]}
      />
      {!isModalVisible ? (
        ''
      ) : (
        <Edit
          isModalVisible={isModalVisible}
          isShowModal={isShowModal}
          actionRef={actionRef}
          editId={editId}
          cateData={cateData}
        />
      )}
    </PageContainer>
  );
};

export default Index;
